package com.oedtech.esl.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.RateLimiter;
import com.oedtech.esl.json.SNJSONObject;
import com.oedtech.esl.model.SNModel.SNEslFirmware;
import com.oedtech.esl.repository.sys.StoreDao;
import com.oedtech.esl.service.SNService.InterfacesService;
import com.oedtech.esl.service.eslService.ApService;
import com.oedtech.esl.service.eslService.EslTabService;
import com.oedtech.esl.service.nettyService.DataService;
import com.oedtech.esl.service.securityService.StoreService;
import com.oedtech.esl.socket.BsChannelMap;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author QiuLongYu
 * @Date 2019/7/26
 * 苏宁接口
 */
@RestController
@RequestMapping("/api3")
public class SNInterfaceController extends BaseController{

    @Autowired
    private InterfacesService interfacesService;
    @Autowired
    private ApService apService;
    @Autowired
    private EslTabService eslTabService;



    /**
     * 为门店绑定AP 接口
     * @param jo   基站mac地址
     * @param storeCode 门店编码
     * @return
     */
    @RequestMapping(value = "/{user}/user/ap",method= RequestMethod.PUT)
    public SNJSONObject bindAp(@RequestBody JSONObject jo, @PathVariable("user")String storeCode){
        try{
            Object macOb=jo.get("mac");

            if(macOb==null)new SNJSONObject("2","mac为空",storeCode);
            String mac=(String)macOb;
            logger.info("SN bind ap and storeCode:apMac[{}],storeCode[{}]",mac,storeCode);
            String msg=apService.bindApAndStoreCode(mac, storeCode);

            if(msg==null){
                return new SNJSONObject(storeCode);
            }
            return new SNJSONObject("2",msg,storeCode);
        }catch (Exception e){
            return new SNJSONObject("2",e.getMessage(),storeCode);
        }


    }

    /**
     * 为门店解绑AP接口
     * @param storeCode  门店编码
     * @param apmac 基站MAC地址
     * @return
     */
    @RequestMapping(value = "/{user}/user/ap/{apmac}",method= RequestMethod.DELETE)
    public SNJSONObject unbindAp(@PathVariable("user")String storeCode,@PathVariable("apmac")String apmac){
        try{
            logger.info("SN unbind ap and storeCode:apMac[{}],storeCode[{}]",apmac,storeCode);
            String msg=apService.unbindApAndStoreCode(apmac);
            if(msg==null){
                return new SNJSONObject(storeCode);
            }
            return new SNJSONObject("2",msg,storeCode);
        }catch (Exception e){
            return new SNJSONObject("2",e.getMessage(),storeCode);
        }

    }

    /**
     * 获取ESL固件信息
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/esls/firmwares",method= RequestMethod.GET)
    public JSONObject returnEslFirmware()  {
        logger.info("SN get firmwares");
       JSONObject jo= new JSONObject();
        try{
            Map<String,SNEslFirmware>map=eslTabService.findAllFirmware();
            jo.put("status_no",0);
            jo.put("errmsg", null);
            jo.put("data", map);
            return jo;
        }catch (Exception e){
            logger.error("",e);
            jo.put("status_no",2);
            jo.put("errmsg", e.getMessage());
            return jo;
        }



    }

    @Value("${sn.imgInterface.permitsPerSecond}")
    private Integer permitsPerSecond;//令牌桶每秒生成令牌数



    private RateLimiter rateLimiter;//令牌桶

    @PostConstruct
    public void init(){
        this.rateLimiter=RateLimiter.create(permitsPerSecond);
    }
    /**
     * 屏幕更新接口
     * @param user 门店编码
     * @param tinyIP  价签ID
     * @param jo   发送的商品数据
     * @return
     */
    @RequestMapping(value = "/{user}/esls/{id}/screen",method= RequestMethod.PUT)
    public SNJSONObject getEslImg(@PathVariable("user")String user,@PathVariable("id")String tinyIP, @RequestBody JSONObject jo){
        if(!rateLimiter.tryAcquire(500, TimeUnit.MILLISECONDS)){
            return new SNJSONObject("2","访问过于频繁",user);
        }
        logger.info("SN push image:tinyIP[{}],storeCode[{}]",tinyIP,user);
        try{
        String msg=interfacesService.imgManager(user,tinyIP,jo);
        if(msg!=null){
            return new SNJSONObject("2",msg,user);
        }
            return new SNJSONObject("1",null,user);  //返回1表示接收成功，等待更新中
        }catch (Exception e){
            logger.error("",e);
            return new SNJSONObject("2",e.getMessage(),user);

        }

    }

    /**
     * 测试 ，生成苏宁发送商品图片的json数据
     * @throws IOException
     */
//    public void t1() throws IOException {
//        File file = new File("D:\\java\\qly\\项目\\努比亚苏宁项目\\苏宁全新接口方案\\2.9待更新.txt");
//        FileInputStream fis = new FileInputStream(file);
//        byte[]b=new byte[(int)file.length()];
//        fis.read(b);
//        fis.close();
//        JSONObject jo = new JSONObject();
//
//        jo.put("sid","12345");
//        jo.put("back_url", "www.esllet.top:9000");
//        jo.put("name", "测试esl图片接收接口");
//        jo.put("default_page_id","2");
//
//
//        List<Map<String, Object>> list = new ArrayList<>();
//        Map<String, Object> map = new HashMap<>();
//        map.put("id","0");
//        map.put("name", "测试");
//        map.put("image", new String(b));
//        list.add(map);
//        jo.put("pages", list);
//    }





    @Autowired
    private DataService dataService;

//    @RequestMapping("P13/{password}/{flag}")
    public Object t13(@PathVariable("password")String password, @PathVariable("flag")Integer flag){
        if(!"esllet".equals(password)){
            return "request denies";
        }
        if(flag!=0&&flag!=1){
            return "flag error";
        }
        Collection<Channel> list = BsChannelMap.getInstance().values();
//        for(Channel channel:list){
//            dataService.sendP13(channel,flag);
//        }
        return "ok";
    }



}
